package com.lwx.bus.controller;


import com.lwx.bus.domain.Goods;
import com.lwx.bus.domain.Provider;
import com.lwx.bus.service.GoodsService;
import com.lwx.bus.service.ProviderService;
import com.lwx.sys.utils.DataGridView;
import com.lwx.sys.utils.ResultObj;
import com.lwx.sys.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 商品管理
 * @author lwx
 * @since 2020-04-21
 */
@RestController
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProviderService providerService;

    @GetMapping("/loadAllGoods")
    public DataGridView loadAllGoods(GoodsVo goodsVo){
        DataGridView dataGridView = goodsService.loadAllGoods(goodsVo);
        List<Goods> data = (List<Goods>) dataGridView.getData();
        for (Goods good: data) {
            Provider provider = providerService.selectProviderById(good.getProviderid());
            good.setProvidername(provider.getProvidername());
        }
        return new DataGridView(data);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/deleteGoods")
    public ResultObj deleteGoods(Integer id){
        try {
            goodsService.deleteGoods(id);
            return ResultObj.DELETE_SUCESS;
        }catch (Exception e){
            return ResultObj.DELETE_ERROR;
        }
    }

    //批量删除
    @DeleteMapping("/batchDeleteGoods")
    public ResultObj batchDeleteGoods(Integer[] ids){
        try {
            goodsService.batchDeleteGoods(ids);
            return ResultObj.DELETE_SUCESS;
        }catch (Exception e){
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 添加商品
     * @param goods
     * @return
     */
    @PostMapping("/addGoods")
    public ResultObj addGoods(Goods goods){
        try {
            goodsService.addGoods(goods);
            return ResultObj.ADD_SUCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 更新商品
     * @param goods
     * @return
     */
    @PostMapping("/updateGoods")
    public ResultObj updateGoods(Goods goods){
        try {
            goodsService.updateGoods(goods);
            return ResultObj.ADD_SUCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @GetMapping("/loadGoodsById")
    public DataGridView loadGoodsById(Integer id){
        return new DataGridView(goodsService.getById(id));

    }

}

